//
//  HXDTabBar.swift
//  weibo
//
//  Created by huxuedong on 15/12/5.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

//protocol HXDTabBarDelegate: NSObjectProtocol {
//    func plusButtonClick()
//}

class HXDTabBar: UITabBar {
    
//    weak var delegater: HXDTabBarDelegate?
    //定义闭包变量
    var plusButtonClosure: (() -> ())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载中间的添加按钮
    lazy var plusButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "plusButtonClick", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        return button
    }()
    
    @objc private func plusButtonClick() {
        //执行闭包
        plusButtonClosure?()
    }
    
    func setupUI() {
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(plusButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        plusButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        let childW = frame.width / 5
        var index = 0
        //遍历tabBar的子控件，设置子控件的位置
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                let childX = CGFloat(index) * childW
                childView.frame = CGRect(x: childX, y: 0, width: childW, height: frame.height)
                index++
                if index == 2 {
                    index++
                }
            }
        }
    }

}
